﻿using Microsoft.Extensions.Logging;
using Nucleic.Core.DoMain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NFine.Application.User;
using Nucleic.Core.Utils.hebcz;
using Newtonsoft.Json;
using YinLong.Tool.Net.HttpHelperMin;
using WmsToVna.Util;

namespace Nucleic.Core.Utils
{
    public class TaskManager
    {

       
        public void Run()
        {
            while (true)
            {
                  NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"->[轮询刷新银行状态]----------轮询-------");

                var ordersIds =  SqlSugarFactory.Instance.Queryable<book_info>().Where(it =>
                it.ins_time.AddMinutes(3) >= DateTime.Now&&it.status=="0").Select(it=>it.orders_id).ToList();
                foreach (var orders_id in ordersIds)
                {

                      NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------开始-------");
                    var book = SqlSugarFactory.Instance.Queryable<book_info>().First(i => i.orders_id == orders_id);
                    if (book == null)
                    {
                          NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->预约信息异常-------");
                          NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------结束-------");
                        continue;
                    }
                    if (book.status != "0")
                    {
                          NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->订单状态不支持-------");
                          NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------结束-------");
                        continue;
                    }
                    var patient = SqlSugarFactory.Instance.Queryable<patient_info>().First(i => i.pat_id == book.pat_id);
                    if (patient == null)
                    {
                          NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->患者信息异常-------");
                          NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------结束-------");
                        continue;
                    }

                    JHRefundApp jhRefundApp = new JHRefundApp();
                    xmlToolApp XMLToolApp = new xmlToolApp();
                    //查询建行本订单金额
                    string returnStr = jhRefundApp.GetOrder(orders_id);
                      NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->患者姓名{patient.name},查询建行本订单:{returnStr}");
                    //建行订单状态 成功000000
                    var code = XMLToolApp.GetTextBydoc(returnStr, "RETURN_CODE");
                      NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->:患者姓名:" + patient.name + ",reutrncode:" + code);

                    if (code == "000000")
                    {
                        var sate = XMLToolApp.GetTextBydoc(returnStr, "ORDER_STATUS");
                        //0:失败,1:成功,2:待银行确认,3:已部分退款,4:已全额退款,5:待银行确认
                        var dt = DateTime.Now;
                        if (sate == "1")
                        {
                            book.status = "1";
                            book.update_time = dt;
                            SqlSugarFactory.Instance.Updateable(book).ExecuteCommand();

                            var item = SqlSugarFactory.Instance.Queryable<check_item>().First(i => i.item_id == book.item_id);
                            var itemtype = SqlSugarFactory.Instance.Queryable<check_type>().First(i => i.item_id == book.item_id);

                            order_info order_ = SqlSugarFactory.Instance.Queryable<order_info>().First(i => i.orders_id == book.orders_id);
                            if (order_ == null)
                            {
                                order_ = new order_info
                                {
                                    pay_time = dt,
                                    pat_id = book.pat_id,
                                    appo_id = book.appo_id,
                                    item_id = book.item_id,
                                    price = item.price,
                                    num = itemtype.num,
                                    orders_id = book.orders_id,
                                    wx_order_no = "建行",
                                    status = "0",
                                    invoiceStatus = 0
                                };
                                if (patient != null)
                                {
                                    order_.tel = patient.tel;
                                    order_.idnum = patient.idnum;
                                    order_.pat_name = patient.name;
                                }
                                SqlSugarFactory.Instance.Insertable<order_info>(order_).ExecuteCommand();
                                  NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->写入数据库");
                            }


                            //发票处理------------------------
                            //查询开票状态
                            var invStatus = hebczUtil.invoicestatus(orders_id);
                              NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                            if (invStatus.code < 1 || invStatus.data.Count == 0 || invStatus.data[0].state == "0")
                            {
                                  NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->申请发票");
                                mkomedicaleinvoiceModel model = new mkomedicaleinvoiceModel()
                                {
                                    einvoicespecimen = "1",
                                    issuedate = dt.ToString("yyyyMMdd"),
                                    issuetime = dt.ToString("hh:mm:ss"),
                                    payerpartytype = "1",
                                    payerpartyname = patient.name,
                                    totalamount = double.Parse(item.price.ToString()).ToString(),
                                    bizcode = orders_id,
                                    handlingperson = hebczConst.handlingperson,
                                    checker = hebczConst.checker,
                                    fundpayamount = "0",
                                    otherpayamount = "0",
                                    accountpayamount = "0",
                                    ownpayamount = double.Parse(item.price.ToString()).ToString(),
                                    //relatedinvoicecode = "1253",
                                    //relatedinvoicenumber = orders_id,
                                };
                                model.details.Add(new details
                                {
                                    itemcode = hebczConst.item_code,
                                    itemname = hebczConst.item_name,
                                    itemamount = double.Parse(item.price.ToString()).ToString(),

                                });
                                model.auxdetails.Add(new auxdetails
                                {
                                    auxitemrelatedcode = hebczConst.item_code,
                                    auxitemrelatedname = hebczConst.item_name,
                                    auxitemname = item.name,
                                    auxitemamount = double.Parse(item.price.ToString()).ToString()
                                });
                                HttpHelperMin http = new HttpHelperMin();
                                HttpItemMin httpitem = new HttpItemMin()
                                {
                                    URL = hebczConst.Url + "/mkomedicaleinvoice",
                                    Method = "POST",
                                    ContentType = "application/json",
                                    Postdata = JsonConvert.SerializeObject(model),
                                };
                                var resule = http.GetHtml(httpitem);
                                  NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->申请发票返回:" + resule.Html);
                                invStatus = JsonConvert.DeserializeObject<ReturnData<MeInvoiceStatusDto>>(resule.Html);

                                if (invStatus != null && invStatus.code == 1)
                                {
                                    //查询开票状态
                                    invStatus = hebczUtil.invoicestatus(orders_id);
                                      NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                                    //如果没有获取过，申请电子发票
                                    if (invStatus != null && invStatus.code == 1 && invStatus.data.Count > 0 && invStatus.data[0].state != "0")
                                    {
                                        order_.einvoicecode = invStatus.data[0].einvoicecode;
                                        order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                                        order_.randomnumber = invStatus.data[0].randomnumber;
                                        order_.invoiceStatus = 1;
                                        SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                                    }

                                }
                            }
                            else
                            {
                                order_.einvoicecode = invStatus.data[0].einvoicecode;
                                order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                                order_.randomnumber = invStatus.data[0].randomnumber;
                                order_.invoiceStatus = 1;
                                SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                            }

                              NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]->支付成功-------");
                              NLog.LogManager.GetLogger(NlogConfig.NlogLogger.Log.ToString()).Debug($"[{orders_id}]->[轮询刷新银行状态]----------结束-------");
                 
                        }
                     
                    }
                  
                 
                }
                Thread.Sleep(100);
            }
        }
    }
}
